package com.lsa.letcode.the105.btZigzagTrav;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.lsa.letcode.common.TreeNode;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    	return levelOrder2(root);
    }
    
    /**
     * Using two queue
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder2(TreeNode root) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	if (root == null) {
    		return result;
    	}
    	
    	LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
    	LinkedList<TreeNode> queueNext = new LinkedList<TreeNode>();
        queue.add(root);
        
        List<Integer> curLevel = new ArrayList<>();
        boolean isOdd = true;
        while(!queue.isEmpty() || !queueNext.isEmpty()) {
        	if (!queue.isEmpty()) {
        		TreeNode head = queue.poll();
        		curLevel.add(head.val);
        		if (head.left != null) {
        			queueNext.add(head.left);
    			}
    			if (head.right != null) {
    				queueNext.add(head.right);
    			}
        	}
        	else {
        		if (!isOdd) {
        			Collections.reverse(curLevel);
        		}
        		isOdd = !isOdd;
        		result.add(curLevel);
        		curLevel = new ArrayList<Integer>();
        		LinkedList<TreeNode> t = queue;
        		queue = queueNext;
        		queueNext = t;
        	}
        }
        if (!isOdd) {
			Collections.reverse(curLevel);
		}
        result.add(curLevel);
        
        return result;
    }
}